local cjson = require "cjson"

function get_cookies()
  local cookies = ngx.header["Set-Cookie"] or {}
  if type(cookies) == "string" then
    cookies = {cookies}
  end
  return cookies
end


function add_cookie(cookie)
  local cookies = get_cookies()
  table.insert(cookies, cookie)
  ngx.header['Set-Cookie'] = cookies
end



local arg = ngx.req.get_uri_args()

if ngx.var.request_uri == '/favicon.ico' then
	return
end

local notLogin = false

local cookieToken = ngx.var['cookie_x-access-token']
ngx.log(ngx.INFO, 'cookieToken='..(cookieToken or ''))
local token = arg.token or cookieToken

if token then
    local checkUrl = "/sso/check?token=".. token
	--ngx.say(checkUrl)
	local res = ngx.location.capture(checkUrl)
	if res.status==200 then
		local resbody = cjson.decode(res.body)
		if resbody.code==0 then
			-- do nothing
		elseif resbody.code==20001 then
			notLogin = true
		elseif resbody.code==20002 then
			ngx.say('没有权限访问当前页面!')
		else
			ngx.say(resbody.message)
		end
	else
		ngx.say(cjson.encode(res))
	end
else
	notLogin = true
end


if notLogin then
	ngx.log(ngx.INFO, 'curr path = '..ngx.var.request_uri)
	return ngx.redirect("http://gsso.58.com/login?url=http://test.58.com" .. ngx.var.request_uri)
elseif not cookieToken then
	ngx.log(ngx.INFO, 'set token cookie:'..token)
	add_cookie("x-access-token=".. token .."; Path=/; Domain=.58.com")
	add_cookie("x-access-token=".. token .."; Path=/")
end